import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Statistics extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException,
	IOException {
		String query="SELECT id, player1, player2, winner FROM history";
		ResultSet result = PostgresDB.sendQuery(query);
		int id;
		String pl1;
		String pl2;
		String winner;

		String beginHTML="<table id='historyTab'>";
		String endHTML="</table>";
		String temp="";
		String info="'class='info' src='images/info.png' alt='User statistics'></img>";
		String medal="<img id='medal' src='images/medal.png' alt='User statistics'></img>";
		
		try {
			while (result.next()) { // process results one row at a time
			    id = result.getInt(1);
			    pl1 = result.getString(2);
			    pl2 = result.getString(3);
			    winner=result.getString(4);
			    String line="";
			   
			    if(winner.equals(pl1)){
			    	line="<tr><td>"+id+"</td><td>"+medal+pl1+"<img id='"+pl1+info+"</td><td>"+pl2+"<img id='"+pl2+info+"</td></tr>";
			    }
			    else{
			    	line="<tr><td>"+id+"</td><td>"+pl1+"<img id='"+pl1+info+"</td><td>"+medal+pl2+"<img id='"+pl2+info+"</td></tr>";
			    }
			    temp=temp+line;
			  }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		out.print(beginHTML+temp+endHTML);
		out.flush();
	}
		
	public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException,
	IOException {
		String username=req.getParameter("user").toString();
		String query="SELECT wins, loses, ratio FROM users WHERE username ='"+username+"';";
		ResultSet result = PostgresDB.sendQuery(query);
		int wins=0;
		int loses=0;
		float ratio=0;
		
	    try {
			while (result.next()) { // process results one row at a time
			    wins = result.getInt(1);
			    loses = result.getInt(2);
			    ratio = result.getFloat(3);
			  }
		} catch (SQLException e) {
			e.printStackTrace();
		}
	    
	    response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		String HTML="<div id='dialog' title='Statistics for user "+username+":'> </br>" +
				"<b>Wins: </b>"+wins+"</br>" +
				"<b>Loses: </b>"+loses+"</br>"+ 
				"<b>Ratio: </b>"+ratio+"</div>"; 

		
		out.print(HTML);
		out.flush();
	        
	}
}


